import { useState } from 'react'
import { Card, Table, Button, Input, Select, Space, Tag, message, Modal, Form, InputNumber } from 'antd'
import { PlusOutlined, SearchOutlined, ReloadOutlined, EditOutlined, DeleteOutlined, UserOutlined, TeamOutlined, CrownOutlined, StarOutlined } from '@ant-design/icons'
import './index.scss'

const UserGroups = () => {
  const [loading, setLoading] = useState(false)
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editingGroup, setEditingGroup] = useState(null)
  const [form] = Form.useForm()
  
  // 搜索表单状态
  const [searchForm, setSearchForm] = useState({
    groupName: '',
    status: 'all'
  })

  // 模拟数据
  const mockData = [
    {
      key: '1',
      groupId: 3001,
      groupName: 'VIP会员',
      groupIcon: <CrownOutlined />,
      groupColor: '#faad14',
      memberCount: 1256,
      description: '付费VIP会员，享受专属权益',
      maxBorrowBooks: 10,
      borrowDays: 60,
      priority: 1,
      status: '启用',
      createTime: '2021-01-15 10:30'
    },
    {
      key: '2',
      groupId: 3002,
      groupName: '普通会员',
      groupIcon: <UserOutlined />,
      groupColor: '#1890ff',
      memberCount: 8542,
      description: '注册用户默认分组',
      maxBorrowBooks: 5,
      borrowDays: 30,
      priority: 3,
      status: '启用',
      createTime: '2021-01-15 10:35'
    },
    {
      key: '3',
      groupId: 3003,
      groupName: '学生会员',
      groupIcon: <StarOutlined />,
      groupColor: '#52c41a',
      memberCount: 3245,
      description: '学生用户专属分组',
      maxBorrowBooks: 8,
      borrowDays: 45,
      priority: 2,
      status: '启用',
      createTime: '2021-02-20 14:20'
    },
    {
      key: '4',
      groupId: 3004,
      groupName: '企业会员',
      groupIcon: <TeamOutlined />,
      groupColor: '#722ed1',
      memberCount: 856,
      description: '企业用户团体分组',
      maxBorrowBooks: 15,
      borrowDays: 90,
      priority: 1,
      status: '启用',
      createTime: '2021-03-10 09:15'
    },
    {
      key: '5',
      groupId: 3005,
      groupName: '试用会员',
      groupIcon: <UserOutlined />,
      groupColor: '#8c8c8c',
      memberCount: 425,
      description: '试用期用户分组',
      maxBorrowBooks: 2,
      borrowDays: 15,
      priority: 4,
      status: '禁用',
      createTime: '2021-04-05 16:45'
    }
  ]

  // 表格列配置
  const columns = [
    {
      title: '分组ID',
      dataIndex: 'groupId',
      key: 'groupId',
      width: 100,
      align: 'center'
    },
    {
      title: '分组信息',
      key: 'groupInfo',
      width: 250,
      render: (_, record) => (
        <div className="group-info-cell">
          <div className="group-icon" style={{ background: record.groupColor }}>
            {record.groupIcon}
          </div>
          <div className="group-details">
            <div className="group-name">{record.groupName}</div>
            <div className="group-desc">{record.description}</div>
          </div>
        </div>
      )
    },
    {
      title: '成员数量',
      dataIndex: 'memberCount',
      key: 'memberCount',
      width: 120,
      align: 'center',
      sorter: (a, b) => a.memberCount - b.memberCount,
      render: (count) => (
        <span className="member-count">{count.toLocaleString()}</span>
      )
    },
    {
      title: '借阅权限',
      key: 'borrowPermission',
      width: 180,
      render: (_, record) => (
        <div className="permission-cell">
          <div className="permission-item">
            <span className="label">最多借阅：</span>
            <span className="value">{record.maxBorrowBooks} 本</span>
          </div>
          <div className="permission-item">
            <span className="label">借阅天数：</span>
            <span className="value">{record.borrowDays} 天</span>
          </div>
        </div>
      )
    },
    {
      title: '优先级',
      dataIndex: 'priority',
      key: 'priority',
      width: 100,
      align: 'center',
      sorter: (a, b) => a.priority - b.priority,
      render: (priority) => {
        const colorMap = {
          1: 'red',
          2: 'orange',
          3: 'blue',
          4: 'default'
        }
        return <Tag color={colorMap[priority]}>P{priority}</Tag>
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (text) => (
        <Tag color={text === '启用' ? 'success' : 'default'}>{text}</Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button type="link" size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record)}>
            删除
          </Button>
        </Space>
      )
    }
  ]

  // 搜索
  const handleSearch = () => {
    setLoading(true)
    setTimeout(() => {
      message.success('搜索成功')
      setLoading(false)
    }, 500)
  }

  // 重置
  const handleReset = () => {
    setSearchForm({
      groupName: '',
      status: 'all'
    })
    message.info('已重置搜索条件')
  }

  // 新建分组
  const handleCreate = () => {
    setEditingGroup(null)
    form.resetFields()
    setIsModalVisible(true)
  }

  // 编辑分组
  const handleEdit = (record) => {
    setEditingGroup(record)
    form.setFieldsValue(record)
    setIsModalVisible(true)
  }

  // 删除分组
  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除分组"${record.groupName}"吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        message.success('删除成功')
      }
    })
  }

  /**
   * 保存分组信息
   * 验证表单并提交数据
   */
  const handleSave = () => {
    form.validateFields().then(values => {
      // TODO: 调用API保存分组信息
      message.success(editingGroup ? '修改成功' : '创建成功')
      setIsModalVisible(false)
    })
  }

  // 行选择
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedKeys) => {
      setSelectedRowKeys(selectedKeys)
    }
  }

  return (
    <div className="reader-groups-container">
      {/* 搜索表格 */}
      <Card className="search-card" title="查询表格">
        <div className="search-form">
          <div className="form-row">
            <div className="form-item">
              <label>分组名称</label>
              <Input
                placeholder="请输入分组名称"
                value={searchForm.groupName}
                onChange={(e) => setSearchForm({ ...searchForm, groupName: e.target.value })}
              />
            </div>
            <div className="form-item">
              <label>状态</label>
              <Select
                value={searchForm.status}
                onChange={(value) => setSearchForm({ ...searchForm, status: value })}
              >
                <Select.Option value="all">全部</Select.Option>
                <Select.Option value="enabled">启用</Select.Option>
                <Select.Option value="disabled">禁用</Select.Option>
              </Select>
            </div>
            <div className="form-item form-actions">
              <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                查询
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </div>
          </div>
        </div>
      </Card>

      {/* 统计卡片 */}
      <div className="stats-cards">
        <Card className="stat-card">
          <div className="stat-content">
            <div className="stat-info">
              <div className="stat-label">总分组数</div>
              <div className="stat-value">12</div>
            </div>
            <div className="stat-icon total">
              <TeamOutlined />
            </div>
          </div>
        </Card>
        <Card className="stat-card">
          <div className="stat-content">
            <div className="stat-info">
              <div className="stat-label">总成员数</div>
              <div className="stat-value">14,324</div>
            </div>
            <div className="stat-icon members">
              <UserOutlined />
            </div>
          </div>
        </Card>
        <Card className="stat-card">
          <div className="stat-content">
            <div className="stat-info">
              <div className="stat-label">VIP会员</div>
              <div className="stat-value">1,256</div>
            </div>
            <div className="stat-icon vip">
              <CrownOutlined />
            </div>
          </div>
        </Card>
        <Card className="stat-card">
          <div className="stat-content">
            <div className="stat-info">
              <div className="stat-label">活跃分组</div>
              <div className="stat-value">8</div>
            </div>
            <div className="stat-icon active">
              <StarOutlined />
            </div>
          </div>
        </Card>
      </div>

      {/* 操作按钮和表格 */}
      <Card className="table-card">
        <div className="table-toolbar">
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
            新增分组
          </Button>
        </div>

        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={mockData}
          loading={loading}
          pagination={{
            total: 12,
            current: 1,
            pageSize: 50,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100']
          }}
          scroll={{ x: 1300 }}
        />
      </Card>

      {/* 新建/编辑分组弹窗 */}
      <Modal
        title={editingGroup ? '编辑分组' : '新建分组'}
        open={isModalVisible}
        onOk={handleSave}
        onCancel={() => setIsModalVisible(false)}
        width={600}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            maxBorrowBooks: 5,
            borrowDays: 30,
            priority: 3,
            status: '启用'
          }}
        >
          <Form.Item
            label="分组名称"
            name="groupName"
            rules={[{ required: true, message: '请输入分组名称' }]}
          >
            <Input placeholder="请输入分组名称" />
          </Form.Item>

          <Form.Item
            label="分组描述"
            name="description"
            rules={[{ required: true, message: '请输入分组描述' }]}
          >
            <Input.TextArea rows={3} placeholder="请输入分组描述" />
          </Form.Item>

          <Form.Item
            label="最多借阅数量"
            name="maxBorrowBooks"
            rules={[{ required: true, message: '请输入最多借阅数量' }]}
          >
            <InputNumber min={1} max={50} style={{ width: '100%' }} addonAfter="本" />
          </Form.Item>

          <Form.Item
            label="借阅天数"
            name="borrowDays"
            rules={[{ required: true, message: '请输入借阅天数' }]}
          >
            <InputNumber min={1} max={365} style={{ width: '100%' }} addonAfter="天" />
          </Form.Item>

          <Form.Item
            label="优先级"
            name="priority"
            rules={[{ required: true, message: '请选择优先级' }]}
          >
            <Select>
              <Select.Option value={1}>P1 - 最高</Select.Option>
              <Select.Option value={2}>P2 - 高</Select.Option>
              <Select.Option value={3}>P3 - 中</Select.Option>
              <Select.Option value={4}>P4 - 低</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="状态"
            name="status"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select>
              <Select.Option value="启用">启用</Select.Option>
              <Select.Option value="禁用">禁用</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default UserGroups
